/*
 * This file is part of LangMan.
 *
 * LangMan is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * LangMan is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LangMan.  If not, see <http://www.gnu.org/licenses/>.
 */

package langman;

import javafx.application.Platform;
import langman.business.data.TranslationException;
import langman.business.data.TranslationService;
import langman.business.data.model.LanguageSet;
import langman.business.io.LanguageLoaderService;
import langman.business.profiles.Profile;
import langman.business.profiles.ProfileService;
import langman.gui.ControlSelectionService;
import langman.gui.languagetable.LanguageTable;
import langman.util.async.StatusTask;
import langman.util.doping.Context;
import langman.util.doping.Inject;
import langman.util.doping.SingletonBean;

import java.util.List;

@SingletonBean
public class AppInitializationTask extends StatusTask<Void> {

    private final Context context;

    @Inject
    public AppInitializationTask(Context context) {
        this.context = context;
    }

    @Override
    protected Void call() throws Exception {
        readLanguages(context);

        ControlSelectionService bean = context.getBean(ControlSelectionService.class);
        bean.selectControlLater(LanguageTable.class);

        return null;
    }

    private void readLanguages(Context context) throws TranslationException {
        ProfileService profileService = context.getBean(ProfileService.class);
        Profile selectedProfile = profileService.getSelectedProfile();

        LanguageLoaderService languageLoaderService = context.getBean(LanguageLoaderService.class);
        languageLoaderService.readConfig(selectedProfile);

        initTranslationService(context, languageLoaderService);
    }

    private void initTranslationService(Context context, LanguageLoaderService languageLoaderService) throws TranslationException {
        Platform.runLater(() -> {
            TranslationService translationService = context.getBean(TranslationService.class);

            List<LanguageSet> sets = languageLoaderService.getSets();
            if (sets.isEmpty()) {
                return;
            }

            translationService.setSets(sets);
            translationService.selectSet(sets.get(0));
        });
    }
}
